import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'package:hixing_app/const/gaps.dart';
import 'package:hixing_app/views/test_view/ble_machine/current_connect_device.dart';

class ScanDeviceItem extends StatefulWidget {
  const ScanDeviceItem({super.key, required this.itemData, this.onTap});

  final ScanResult itemData;
  final Function(bool)? onTap;

  @override
  _ScanDeviceItemState createState() => _ScanDeviceItemState();
}

class _ScanDeviceItemState extends State<ScanDeviceItem> {
  late StreamSubscription<BluetoothConnectionState>
      _connectionStateSubscription;
  BluetoothConnectionState _connectionState =
      BluetoothConnectionState.disconnected;

  bool get isConnected {
    return _connectionState == BluetoothConnectionState.connected;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _connectionStateSubscription =
        widget.itemData.device.connectionState.listen((state) {
      _connectionState = state;
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  void dispose() {
    _connectionStateSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.all(10),
        child: Row(
          children: [
            Text("rssi：${widget.itemData.rssi}"),
            Gaps.hGap4,
            GestureDetector(
              onTap: () {
                if (isConnected) {
                  Get.to(CurrentConnectDevice(detailData: widget.itemData));
                }
              },
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(widget.itemData.device.advName),
                  SizedBox(
                    width: 180,
                    child: Text(
                      widget.itemData.device.remoteId.toString(),
                      maxLines: 2,
                    ),
                  )
                ],
              ),
            ),
            const Spacer(),
            ElevatedButton(
                onPressed: () {
                  widget.onTap!(isConnected);
                  setState(() {});
                },
                child: Text(isConnected ? "断开" : "连接")),
          ],
        ));
  }
}
